package com.sann.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.Objects;
import java.util.Set;

/**
 * 自定义一个类型扫描过滤器，让 Spring对符合我们自定义规则的类扫描进 Spring容器
 */
@Slf4j
public class MyTypeFilter implements TypeFilter {

    @Override
    public boolean match(MetadataReader metadataReader,
                         MetadataReaderFactory metadataReaderFactory) throws IOException {
        // 获取扫描包下当前遍历类上注解信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        // 获取类的信息
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        // 获取类的资源信息，比如类的所在磁盘位置等
        Resource resource = metadataReader.getResource();

        String className = annotationMetadata.getClassName();
        Set<String> annotationTypes = annotationMetadata.getAnnotationTypes();
        log.info("获取遍历的类名--------->"+className);
        log.info("获取当前遍历类上所有注解[]----------------------------->"+annotationTypes);

        if (Objects.equals("com.sann.filter.MyTypeFilter", className)) {
            return true;//扫描时放行MyTypeFilter类，让该类被Spring容器加载
        }

        return false;
    }
}
